var app = getApp()

Page({
  data:{
    logged: app.globalData.userInfo,
    userInfo: null,
    name: "",
    stuID: "",
    phone: "",
    weChat: "",

    showSubmit: false,
    history: {}
  },

  onLogin(event){
    console.log(event)
    var that = this
    const db = wx.cloud.database({
      env: 'cloud-dev-alpha-3f1k3'
    })
    db.collection('account').get({
      // 查询账户是否存在成功
      success: res=>{
        console.log(res)
        // 账户不存在
        if(res.data.length == 0){
          // 用户拒绝授权，显示提示信息并返回
          if(event.detail.userInfo == null){
            console.log("用户拒绝授权，登录失败！！！")
            wx.showModal({
              title: '授权失败',
              content: '您拒绝了小程序使用您的个人信息，部分功能将无法使用，您可以重新登陆并授权后使用'
            })
            return
          }
          wx.showLoading({
            title: '正在登陆',
          })
          // 获取openid
          wx.cloud.callFunction({
            name: 'login',
            // 获取openid成功
            success: res=>{
              console.log(res)
              app.globalData.openid = res.result._openid
              // 创建账户
              db.collection('account').add({
                data: {
                  userInfo: event.detail.userInfo,
                  name: that.data.name,
                  stuID: that.data.stuID,
                  phone: that.data.phone,
                  weChat: that.data.weChat
                },
                // 创建账户成功
                success: res=>{
                  wx.hideLoading({
                  })
                  // 全局变量赋值，显示用户状态和信息
                  app.globalData.userInfo = event.detail.userInfo
                  console.log(app.globalData.userInfo)
                  app.globalData.logged = true
                  // 绑定数据赋值
                  that.setData({
                    userInfo: app.globalData.userInfo,
                    logged: app.globalData.logged
                  })
                  // 设置缓存数据
                  try{
                    wx.setStorageSync('name', that.data.name)
                    wx.setStorageSync('stuID', that.data.stuID)
                    wx.setStorageSync('phone', that.data.phone)
                    wx.setStorageSync('weChat', that.data.weChat)
                    wx.setStorageSync('openid', app.globalData.openid)
                    wx.setStorageSync('userInfo', that.data.userInfo)
                    wx.setStorageSync('logged', that.data.logged)
                    console.log("设置缓冲区成功！")
                  }catch{
                    console.log("设置缓冲区失败！！！")
                    wx.clearStorageSync({
                      success: res => {
                        console.log("缓冲区已清除！")
                      },
                      fail: res=>{
                        console.log("缓冲区清除失败！！！")
                      }
                    })
                  }
                  // 提示登录成功
                  console.log("登录成功！")
                  wx.showToast({
                    title: '登录成功',
                    icon: 'success',
                    duration: 2000
                  })
                },
                // 创建账户失败
                fail: res=>{
                  console.log("无法创建账户，登录失败！！！")
                  wx.showModal({
                    title: '创建账户失败',
                    content: '无法创建账户，部分功能将无法使用',
                  })
                }
              })
            },
            // 提示openid获取失败
            fail: res=>{
              console.log(res)
              app.globalData.openid = null
              console.log("无法获取openid，登录失败！！！")
              wx.showModal({
                title: '登录失败',
                content: '无法获取openid，部分功能将无法使用'
              })
            }
          })
        }
        // 账户已存在，重新初始化账户信息
        else if(res.data.length == 1) {
          // 用户拒绝授权，显示提示信息并返回
          if(event.detail.userInfo == null){
            console.log("用户拒绝授权，登录失败！！！")
            wx.showModal({
              title: '授权失败',
              content: '您拒绝了小程序使用您的个人信息，部分功能将无法使用，您可以重新登陆并授权后使用'
            })
            return
          }
          // 用户再次授权
          else{
            wx.showLoading({
              title: '正在登录',
            })
            app.globalData.userInfo = event.detail.userInfo
            app.globalData.openid = res.data[0]._openid
            console.log(app.globalData.openid)
            app.globalData.logged = true
            that.setData({
              logged: app.globalData.logged,
              userInfo: app.globalData.userInfo,
              name: res.data[0].name,
              stuID: res.data[0].stuID,
              phone: res.data[0].phone,
              weChat: res.data[0].weChat
            })
            wx.hideLoading({
            })
            // 设置缓存数据
            try{
              wx.setStorageSync('name', res.data[0].name)
              wx.setStorageSync('stuID', res.data[0].stuID)
              wx.setStorageSync('phone', res.data[0].phone)
              wx.setStorageSync('weChat', res.data[0].weChat)
              wx.setStorageSync('openid', app.globalData.openid)
              wx.setStorageSync('userInfo', app.globalData.userInfo)
              wx.setStorageSync('logged', that.data.logged)
              console.log("设置缓冲区成功！")
            }catch{
              console.log("设置缓冲区失败！！！")
              wx.clearStorageSync({
                success: res => {
                  console.log("缓冲区已清除！")
                },
                fail: res=>{
                  console.log("缓冲区清除失败！！！")
                }
              })
            }
            // 更新用户信息
            db.collection('account').doc(res.data[0]._id).update({
              data:{
                userInfo: event.detail.userInfo
              },
              success: res=>{
                console.log("更新账户信息成功！")
              },
              fail: res=>{
                console.log("更新账户信息失败！！！")
              }
            })
          }
        }
        // 存在多个账户，系统发生故障，禁止用户使用
        else{
          console.log("系统故障，存在多个账户！")
          wx.showModal({
            title: '系统故障',
            content: '小程序系统发生故障，请稍后再试'
          })
        }
      },
      // 查询账户是否存在失败
      fail: res=>{
        console.log('云数据库查询账户是否存在失败！！！')
        wx.showModal({
          title: '系统故障',
          content: '小程序系统发生故障，请稍后再试'
        })
      }
    })
  },
    
  inputName(event){
    // 保存历史
    this.data.history.name = this.data.name
    this.data.history.stuID = this.data.stuID
    this.data.history.phone = this.data.phone
    this.data.history.weChat = this.data.weChat
    // 设置新值
    this.setData({
      name: event.detail.value,
      showSubmit: true & this.data.logged
    })
  },
  inputStuID(event){
    // 保存历史
    this.data.history.name = this.data.name
    this.data.history.stuID = this.data.stuID
    this.data.history.phone = this.data.phone
    this.data.history.weChat = this.data.weChat
    // 设置新值
    this.setData({
      stuID: event.detail.value,
      showSubmit: true & this.data.logged
    })
  },
  inputPhone(event){
    // 保存历史
    this.data.history.name = this.data.name
    this.data.history.stuID = this.data.stuID
    this.data.history.phone = this.data.phone
    this.data.history.weChat = this.data.weChat
    // 设置新值
    this.setData({
      phone: event.detail.value,
      showSubmit: true  & this.data.logged
    })
  },
  inputWeChat(event){
    // 保存历史
    this.data.history.name = this.data.name
    this.data.history.stuID = this.data.stuID
    this.data.history.phone = this.data.phone
    this.data.history.weChat = this.data.weChat
    // 设置新值
    this.setData({
      weChat: event.detail.value,
      showSubmit: true  & this.data.logged
    })
  },
  modifyUserInfo(){
    if(!this.data.logged){
      console.log("用户未登录，拒绝提交！！！")
      wx.showToast({
        title: '请登录',
        icon: 'none',
        duration: 2000
      })
      return
    }
    var that = this
    const db = wx.cloud.database({
      env: 'cloud-dev-alpha-3f1k3'
    })
    db.collection('account').get({
      success: res=>{
        console.log(res)
        console.log("获取记录成功")
        if(res.data.length == 1){
          db.collection('account').doc(res.data[0]._id).update({
            data:{
              name: that.data.name,
              stuID: that.data.stuID,
              phone: that.data.phone,
              weChat: that.data.weChat
            },
            // 修改成功
            success: res=>{
              console.log("修改账户信息成功！")
              // 设置缓存数据
              try{
                wx.setStorageSync('name', that.data.name)
                wx.setStorageSync('stuID', that.data.stuID)
                wx.setStorageSync('phone', that.data.phone)
                wx.setStorageSync('weChat', that.data.weChat)
                console.log("设置缓冲区成功！")
              }catch{
                console.log("设置缓冲区失败！！！")
                wx.clearStorageSync({
                  success: res => {
                    console.log("缓冲区已清除！")
                  },
                  fail: res=>{
                    console.log("缓冲区清除失败！！！")
                  }
                })
              }
              wx.showToast({
                title: '修改成功',
                icon: 'success',
                duration: 2000
              })
            },
            // 修改失败
            fail: res=>{
              console.log("更新账户信息失败！！！")
              wx.showModal({
                title: '修改失败',
                content: '账户信息修改失败，请稍后再试',
                complete: res=>{
                  that.setData({
                    showSubmit: false
                  })
                }
              })
            },
            complete: res=>{
              that.setData({
                showSubmit: false
              })
            }
          })
        }
        // 存在多个账户或账户不存在
        else{
          wx.showModal({
            title: '系统故障',
            content: '小程序系统故障，请稍后再试',
            complete: res=>{
              that.setData({
                showSubmit: false
              })
            }
          })
        }
      },
      // 查询失败
      fail: res=>{
        wx.showModal({
          title: '系统故障',
          content: '小程序系统故障，请稍后再试',
        })
      }
    })
  },
  cancelModify(){
    // 恢复原值并隐藏按钮
    this.setData({
      name: this.data.history.name,
      stuID: this.data.history.stuID,
      phone: this.data.history.phone,
      weChat: this.data.history.weChat,
      showSubmit: false
    })
  },
  // 实现自动登录功能
  onLoad(event){
    var that = this
    try{
      app.globalData.logged = wx.getStorageSync('logged')
      app.globalData.userInfo = wx.getStorageSync('userInfo')
      app.globalData.openid = wx.getStorageSync('openid')
      var stName = wx.getStorageSync('name')
      var stStuID = wx.getStorageSync('stuID')
      var stPhone = wx.getStorageSync('phone')
      var stWeChat = wx.getStorageSync('weChat')
      this.setData({
        logged: app.globalData.logged,
        userInfo: app.globalData.userInfo,
        name: stName,
        stuID: stStuID,
        phone: stPhone,
        weChat: stWeChat
      })
    }catch{
      app.globalData.logged = false
      app.globalData.userInfo = null
      app.globalData.openid = null
      that.data.logged = false
      that.data.userInfo = null
      that.data.name = ''
      that.data.stuID = ''
      that.data.phone = ''
      that.data.weChat = ''
      console.log("获取缓冲区失败！！！")
      wx.clearStorageSync({
        success: res => {
          console.log("缓冲区已清除！")
        },
        fail: res=>{
          console.log("缓冲区清除失败！！！")
        }
      })
    } 
  }
})